package com.witmore.neutron.ai.mcp.server.trading.service.impl;

import com.witmore.neutron.ai.mcp.server.trading.dto.ChatCompletionResponse;
import com.witmore.neutron.ai.mcp.server.trading.service.StockNameToCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * 股票名称到代码映射服务实现
 *
 * @author 豆子高
 * @date 2025-01-20
 */
@Slf4j
@Service
public class StockNameToCodeServiceImpl implements StockNameToCodeService {

    @Autowired
    private WebClient webClient;

    @Override
    public String getStockCodeByName(String stockName) {
        log.info("=== 开始股票名称查询 === 输入股票名称: [{}]", stockName);

        // 参数校验
        if (stockName == null || stockName.trim().isEmpty()) {
            log.warn("股票名称参数为空或空字符串");
            return "错误：股票名称不能为空";
        }

        String trimmedStockName = stockName.trim();
        log.info("处理后的股票名称: [{}]", trimmedStockName);

        try {
            // 1. 构建请求体
            Map<String, Object> requestBody = Map.of(
                    "model", "qwen-max",
                    "stream", false,
                    "messages", List.of(
                            Map.of("role", "system", "content", """
                                    你是一个A股股票助手，专门帮助用户根据股票名称查询股票代码，支持模糊查询。
                                    直接返回股票代码。
                                    """),
                            Map.of("role", "user", "content", trimmedStockName)
                    )
            );

            log.info("构建大模型请求体完成 - 模型: qwen-max, 用户输入: [{}]", trimmedStockName);
            log.debug("完整请求体: {}", requestBody);

            // 2. 发起 POST 请求，并直接反序列化到 ChatCompletionResponse 对象
            ChatCompletionResponse response = webClient.post()
                    .uri("/v1/chat/completions")
                    .bodyValue(requestBody)
                    .retrieve()
                    .bodyToMono(ChatCompletionResponse.class)
                    .block(Duration.ofSeconds(30));
            ChatCompletionResponse.Choice choice = response.getChoices().get(0);
            return choice.getMessage().getContent();

        } catch (Exception e) {
            log.error("构建大模型请求时发生异常 - 股票名称: [{}], 异常类型: {}, 异常信息: {}",
                    trimmedStockName, e.getClass().getSimpleName(), e.getMessage(), e);
            return "查询失败: " + e.getMessage();
        }
    }

}
